import os
import sys

from PyQt5.QtCore import QObject, QThread
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QFileDialog
from subprocess import Popen, PIPE
from push_ui import Ui_Form


class Work(QObject):
    def __init__(self, video_file_path):
        super().__init__()
        self.video_file_path = video_file_path

    def run(self):
        video_file_path = self.video_file_path

        os.chdir(os.path.split(video_file_path)[0])

        command = [
            "ffmpeg",
            "-re",
            "-i", video_file_path,
            "-vcodec", "libx264",
            "-vprofile", "baseline",
            "-g", "30",
            "-acodec", "aac",
            "-strict", "-2",
            "-f", "flv",
            "rtmp://127.0.0.1:1935/file/stream"
        ]
        process = Popen(command, stdout=PIPE, stderr=PIPE)
        stdout, stderr = process.communicate()
        print(stdout.decode())
        print(stderr.decode())


class MyMainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.w = None
        self.thread = None
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.filepath = ''
        self.ui.pushButton.clicked.connect(self.openFile)
        self.ui.pushButton_2.clicked.connect(self.start_work)

    def openFile(self):
        options = QFileDialog.Options()
        # options |= QFileDialog.DontUseNativeDialog
        self.filepath, _ = QFileDialog.getOpenFileName(self, "选择视频文件", "", "视频文件 (*.mp4 *.avi *.mkv *.mov)",
                                                       options=options)
        if self.filepath:
            print("选择的文件路径:", self.filepath)

    def start_work(self):
        self.thread = QThread()
        self.thread.start()

        self.w = Work(self.filepath)
        self.w.moveToThread(self.thread)
        self.thread.started.connect(self.w.run)  # 添加这行以确保run方法在子线程启动时运行


def main():
    app = QApplication(sys.argv)
    window = MyMainWindow()
    window.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()
